<style lang="stylus" type="text/stylus">
  @import 'policymatch.styl';
</style>

<template>
  <div id='policymatchmodul'>
    <!-- 左边栏 在线政策 -->
    <div class='SidebarLeft'>
      <div class="menuLeft">
        <!-- 菜单选项 -->
        <fundInfo v-if="fundInfoDatas" :fundInfoDatas="fundInfoDatas"
                  :policyToChart="policyToChart"
                  :chartToPolicy="chartToPolicy"
                  @delChartPrizeFun="delChartPrizeFun"
                  @changeFundInfoData="changeFundInfoData"
                  @changePolicyToChart="changePolicyToChart"
                  @refreshAdd="refreshAdd"
                  @refreshSub="refreshSub"></fundInfo>
        <!-- ======= -->
      </div>
    </div>

    <!-- 中间内容 总逻辑图-->
    <div class="centerPicture">
      <span class="conterTittle" @click="consoles">总逻辑图</span>
      <VuePerfectScrollbar id="chart-ps" class="chart-ps">
        <unitChart :unitObj="unitObj"
                   :dragUnUnitObj="dragUnUnitObj"
                   :chartToPolicy="chartToPolicy"
                   :policyToChart="policyToChart"
                   :delChartPrize="delChartPrize"
                   @pointLine="breakUpData"
                   @changeChartToPolicy="changeChartToPolicy"
                   @changePolicyToChart="changePolicyToChart"
                   @unUnitItem="unUnitItem"
                   @changeUnUnitData="changeUnUnitData"
                   @delPolicyPrizeFun="delPolicyPrizeFun"
                   @chartToUnUnitFun="chartToUnUnitFun"></unitChart>
        <div id="chart-ps-canvas" :style="'width='+divWidth,'height='+divHeight"></div>
      </VuePerfectScrollbar>
    </div>

    <!-- 右边列表 解绑的逻辑单元 -->
    <div class="SidebarRight">
      <div class="backspacing">
        <span class="sidebarRightTitle">解绑的逻辑单元</span>
        <div class="hideRight-Arrows" @click="zoomRight()">
          <Icon v-if="shrinkRight" type="ios-arrow-right" class="ios-arrow-right"></Icon>
          <Icon v-else type="ios-arrow-left" class="ios-arrow-right"></Icon>
        </div>
      </div>
      <VuePerfectScrollbar class="policyMatchCardListScroll">
        <unbundlingUnit :unbundlingUnitData="unitObj.nobindproblem"
                        :chartToUnUnit="chartToUnUnit"
                        @unUnitToChartFirts="unUnitToChartFirts"
                        @unUnitItem="unUnitItem"
                        @getUnUnitToChart="getUnUnitToChart"
                        @dragUnUnitToChart="dragUnUnitToChart">
        </unbundlingUnit>
      </VuePerfectScrollbar>

    </div>

    <div class="BottomButton">
      <div class="overallBotton">
        <span class="buttonError" @click="restore"> <span><Icon type="android-close"></Icon></span> 放弃更改并还原</span>
        <span class="buttonSuccess" @click="saveChart"> <span><Icon type="android-done"></Icon></span> 保存并发布</span>
      </div>
    </div>

    <div id="dragInfo">
      <span>123</span>
    </div>
  </div>
</template>

<script type="text/ecmascript-6">
  import $ from "jquery";
  import unitChart from "./unitChart.vue";
  import fundInfo from "./fundInfo";
  import unbundlingUnit from "./unbundlingUnit";

  export default {
    name      : "policymatch",
    data() {
      return {
        divWidth     : 0,
        divHeight    : 0,
        fundInfoDatas: null,
        dragUnUnitObj: {
          obj  : null,
          index: null
        },
        dragMatchObj : null,
        shrinkRight  : true, //右邊欄收縮箭頭

        chartToUnUnit: null,
        chartToPolicy: null,
        policyToChart: null,

        delChartPrize: null,

        unitObj: {
          nobindproblem: [],
          answers      : [
            {
              position: "",
              problems: []
            }
          ]
        }
      };
    },
    components: {
      unitChart,
      fundInfo,
      unbundlingUnit
    },
    computed  : {},
    methods   : {
      getFundInfo() {
        this.ajaxData(
          {
            type: "get",
            url : "/prize/page?type=P&page=1&pageSize=100"
          },
          (res, all) => {
            this.fundInfoDatas = res;
          }
        );
      },
      getUnitData() {
        let unit = [
          {
            position: `first_${(Math.random() * Date.now()).toFixed(0)}`,
            title   : '',
            answers : []
          }
        ];
        unit[0].answers.push({
          position: `unit_${(Math.random() * Date.now()).toFixed(0)}`,
          content : '',
          prizes  : [],
          problems: []
        });
//        this.unitObj.answers[0].problems = unit
        this.ajaxData(
          {type: "get", url: "/prizematch/findMatchingView"},
          (res, all) => {
            this.unitObj.answers[0].problems = res.unitJson.answers.length
              ? res.unitJson.answers
              : unit;
//            this.unitObj.answers[0].problems

            setTimeout(() => {
              this.breakUpData();
            }, 10);
          }
        );
      },
      getUnUnitData() {
        this.ajaxData(
          {
            type: "get",
            url : "/prizematch/getnobindproblem?page=1&pageSize=10"
          },
          res => {
            this.unitObj.nobindproblem = res;
          }
        );
      },
      dragUnUnitToChart(data) {
        this.dragUnUnitObj = data;
        setTimeout(() => {
          this.breakUpData();
        }, 50);
      },
      getUnUnitToChart(data) {
        data.arr.problems.push(data.obj);
        this.unitObj.nobindproblem.splice(data.index, 1);
        this.chartToUnUnit = null;
        setTimeout(() => {
          this.breakUpData();
        }, 50);
      },
      changeUnUnitData(index) {
        this.dragUnUnitObj.obj   = null;
        this.dragUnUnitObj.index = null;
        index ? this.unitObj.nobindproblem.splice(index, 1) : "";
      },
      chartToUnUnitFun(data) {
        this.chartToUnUnit = data;
      },
      changeChartToPolicy(data) {
        this.chartToPolicy = data;
      },
      changePolicyToChart(data) {
        this.policyToChart = data;
      },
      changeFundInfoData({policyId, prizeId, prizesData}) {
        let arr = this.fundInfoDatas.results;
        for (let v of arr) {
          if (v.id == policyId) {
            for (let j of v.prizes) {
              if (j.id == prizeId) {
                j.dataCache = prizesData;
              }
            }
          }
        }
      },
      unUnitToChartFirts(data) {
        this.unitObj.answers[0].problems.unshift(data.item);
        this.unitObj.nobindproblem.splice(data.itemIndex, 1);
        setTimeout(() => {
          this.breakUpData();
        }, 50);
      },
      unUnitItem(item) {
        this.unitObj.nobindproblem = [...item, ...this.unitObj.nobindproblem];
      },
      delPolicyPrizeFun(data) {
        let arr    = this.fundInfoDatas.results;
        let policy = arr.find(v => {
          return v.id == data.policyId;
        });
        let prize  = policy
          ? policy.prizes.find(v => {
            return v.id == data.prizeId;
          })
          : "";
        if (prize) {
          let prizeDataCache = prize.dataCache;
          let problem        = prizeDataCache.find(v => {
            return v.position == data.problemPosition;
          });
          let problemIndex   = prizeDataCache.findIndex(v => {
            return v.position == data.problemPosition;
          });
          if (problem) {
            let answerIndex = problem.answers.findIndex(v => {
              return v.position == data.answerPosition
            });
            problem.answers.splice(answerIndex, 1)
            if (!problem.answers.length) {
              prizeDataCache.splice(problemIndex, 1)
            }
          }
        }
      },
      delChartPrizeFun(data) {
        this.delChartPrize = data;
        this.delPolicyPrizeFun({
          policyId       : data.policyId,
          prizeId        : data.prizeId,
          problemPosition: data.problem.position,
          answerPosition : data.answer.position
        });
      },
      saveChart() {
        this.ajaxData(
          {
            type: "post",
            url : "/prizematch/saveMatchingView",
            data: {
              unitJson: JSON.stringify({unitJson: this.unitObj})
            }
          },
          res => {this.$Message.success('提交成功');}
        );
      },
      restore() {
        this.getFundInfo();
        this.getUnitData();
        this.getUnUnitData();
      },
      refreshAdd(data) {
        let arr    = this.fundInfoDatas.results;
        let policy = arr.find(v => {
          return v.id == data.policyId;
        });
        let prize  = policy
          ? policy.prizes.find(v => {
            return v.id == data.gearsId;
          })
          : "";
        prize.count++;
      },
      refreshSub(data) {
        let arr     = this.fundInfoDatas.results;
        let policy  = arr.find(v => {
          return v.id == data.policyId;
        });
        let prize   = policy
          ? policy.prizes.find(v => {
            return v.id == data.gearsId;
          })
          : "";
        prize.count = data.length;
      },
      makedot(x, y) {
        this.pointDiv =
          "<div class='pointLine' style='height:1px;position:absolute;left:" +
          x +
          "px;top:" +
          y +
          "px;width:1px;background:#33c3ff;overflow:hidden;z-index:0'></div>";
        return this.pointDiv;
      },
      line(x1, y1, x2, y2) {
        var i;
        var slope; //斜率
        var direction; //坐标运动方向
        var tx = x2 - x1;
        var ty = y2 - y1;
        if (tx == 0 && ty == 0) return;
        var points = "";
        var axis; //坐标轴上的坐标
        if (Math.abs(tx) >= Math.abs(ty)) {
          //在x轴上移动
          direction = tx > 0 ? 1 : -1;
          tx        = Math.abs(tx);
          slope     = ty / tx;
          axis      = x1;
          for (i = 0; i < tx; i++) {
            points += this.makedot(axis, y1 + i * slope);
            axis += direction;
          }
        } else {
          //在y轴上移动
          direction = ty > 0 ? 1 : -1;
          ty        = Math.abs(ty);
          slope     = tx / ty;
          axis      = y1;
          for (i = 0; i < ty; i++) {
            points += this.makedot(x1 + i * slope, axis);
            axis += direction;
          }
        }
        var container = document.getElementById("chart-ps-canvas");
        container.innerHTML += points;
      },
      breakUpData() {
        $(".pointLine").remove();
        this.divWidth  = document.getElementById("chart-ps").scrollWidth;
        this.divHeight = document.getElementById("chart-ps").scrollHeight;
        var answers1   = this.unitObj.answers;
        for (var t = 0; t < answers1.length; t++) {
          var childs = answers1[t];
          for (var i = 0; i < childs.problems.length; i++) {
            var problems = childs.problems[i];
            for (var j = 0; j < problems.answers.length; j++) {
              this.answersFormat(problems.answers[j]);
            }
          }
        }
      },
      answersFormat(answers) {
        if (answers.problems != null && answers.problems.length > 0) {
          for (var i = 0; i < answers.problems.length; i++) {
            this.problemFormat(answers.problems[i], answers.position);
          }
        }
      },
      problemFormat(problems, answerId) {
        let pointA = document.getElementById(answerId);
        let pointB = document.getElementById(problems.position);

        function getTop(e) {
          var offset = e.offsetTop;
          if (e.offsetParent != document.getElementById("chart-ps")) {
            if (e.className == "card-con-com first-card") {
              offset -= e.offsetHeight / 2;
            }
            offset += getTop(e.offsetParent);
          }
          return offset;
        }

        function getLeft(e) {
          var offset = e.offsetLeft;
          if (e.offsetParent != document.getElementById("chart-ps"))
            offset += getLeft(e.offsetParent);
          return offset;
        }

        let pointATop  = getTop(pointA) + 16;
        let pointALeft = getLeft(pointA) + 178;
        let pointBTop  = getTop(pointB) + pointB.offsetHeight / 2;
        let pointBLeft = getLeft(pointB);
        setTimeout(() => {
          this.line(pointALeft, pointATop, pointBLeft, pointBTop);
        }, 10);

        if (problems.answers != null && problems.answers.length > 0) {
          for (var i = 0; i < problems.answers.length; i++) {
            this.answersFormat(problems.answers[i]);
          }
        }
      },
      consoles() {
        console.log(this.unitObj.answers[0].problems)
      },
      //獲取Dom元素
      getDomDataRight() {
        var w1                    = document.querySelector(".SidebarLeft");
        this.w1                   = w1;
        //获取右边栏标题
        var sidebarRightTitle     = document.querySelector(".sidebarRightTitle");
        this.sidebarRightTitle    = sidebarRightTitle;
        //获取右边栏列表div
        var policyMatchRightList  = document.querySelector(
          ".policyMatchRightList"
        );
        this.policyMatchRightList = policyMatchRightList;

        var w2  = document.querySelector(".centerPicture");
        this.w2 = w2;
        var w3  = document.querySelector(".SidebarRight");
        this.w3 = w3;
      },
      //右邊欄收縮
      zoomRight() {
        this.shrinkRight = !this.shrinkRight;
        //当左右边栏正常显示的情况下
        if (this.w3.clientWidth >= 398 && this.w1.clientWidth >= 448) {
          this.w3.setAttribute("class", "dd");
          this.w2.setAttribute("class", "cc2");
          this.sidebarRightTitle.setAttribute("class", "sidebarRightTitleHide");
          this.policyMatchRightList.setAttribute(
            "class",
            "policyMatchRightListHide"
          );
        } else if (this.w3.clientWidth >= 398 && this.w1.clientWidth < 448) {
          //当右边栏正常显示、左边栏收起来的情况下
          this.w3.setAttribute("class", "dd");
          this.w2.setAttribute("class", "ff");
          this.sidebarRightTitle.setAttribute("class", "sidebarRightTitleHide");
          this.policyMatchRightList.setAttribute(
            "class",
            "policyMatchRightListHide"
          );
        } else if (this.w3.clientWidth < 398 && this.w1.clientWidth >= 448) {
          //当右边栏收起来、左边栏正常显示的情况下
          this.w3.setAttribute("class", "SidebarRight");
          this.w2.setAttribute("class", "centerPicture");
          this.sidebarRightTitle.setAttribute("class", "sidebarRightTitle");
          this.policyMatchRightList.setAttribute("class", "policyMatchRightList");
        } else if (this.w3.clientWidth < 398 && this.w1.clientWidth < 448) {
          //当左右边栏都收起来的情况下
          this.w3.setAttribute("class", "SidebarRight");
          this.w2.setAttribute("class", "cc");
          this.sidebarRightTitle.setAttribute("class", "sidebarRightTitle");
          this.policyMatchRightList.setAttribute("class", "policyMatchRightList");
        }
      }
    },
    mounted() {
      this.getDomDataRight();
    },
    created() {
      this.restore();
    }
  };
</script>
